<template>
  <div class="container-fluid">
    <el-row :gutter="20">
      <el-button size="default" type="primary" @click="downloadTemplate">
        下载模板
      </el-button>
      <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :auto-upload="true"
        :accept="Sheetjsftstring" :http-request="request" :show-file-list="false">
        <el-button type="primary" size="default">上传文件</el-button>
      </el-upload>
    </el-row>
    <el-row class="margin-top20">
      <el-col>
        <el-table :data="team" style="width: 100%" max-height="500">
          <el-table-column prop="name" label="团队名称" />
          <el-table-column prop="userid" label="团队负责人">
            <template #default="scope">
              <div v-if="scope.row.user?.name">
                {{ scope.row.user?.name }}
              </div>
              <el-select-v2 v-else v-model="scope.row.userid" :options="options(scope.row.name)" placeholder="请选择"
                style="width: 240px" />
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="margin-top20">
      <el-col>
        <el-table :data="tabledata" border style="width: 100%" max-height="500">
          <el-table-column prop="名称" type="index" width="50" />
          <el-table-column prop="名称" label="名称" />
          <el-table-column prop="手机号" label="手机号" />
          <el-table-column prop="学籍号" label="学籍号" />
          <el-table-column prop="密码" label="密码" />
          <el-table-column prop="团队id" label="团队id" width="100" />
          <el-table-column prop="团队名称" label="团队名称" />
          <el-table-column prop="团队角色" label="团队角色" />
          <el-table-column prop="团队分组" label="团队分组" />
          <el-table-column prop="备注" label="备注" />
          <el-table-column prop="学校名称" label="学校名称" />
          <el-table-column prop="错误" fixed="right" label="错误" width="110">
            <template #default="scope">
              <el-tooltip v-if="!!scope.row.iserror" class="item" effect="dark" :content="scope.row.iserror"
                placement="top-start">
                <el-button v-show="scope.row.iserror" type="warning" size="default">
                  警告
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="margin-top20">
      <el-button type="primary" size="default" @click="add" :disabled="!tabledata.length">导入</el-button>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { asyncfindteamusergroup, asyncselectteams, Iobj } from "../../../api";
import { Storekey } from "../../../interface";

import { ElMessage, ElNotification } from "element-plus";
import { union } from 'lodash-es';
import { computed, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { getExceltodownload, getfiletodata2, Sheetjsftstring } from "../../../util/excel";
import { isPhonenum } from "../../../util/RegExp";

const arr: string[] = ["名称", "手机号", "学籍号", "密码", "团队id", "团队名称", "团队角色", "备注", "学校名称", "团队分组"];

const store = useStore(Storekey);

const p = defineProps<{ close: boolean, teamInfo: Studycodemodel.Iteam, closeDrawer: () => {} }>()
// 码客行
// const tenant_id = undefined
const tenant_id = p.teamInfo.tenant_id || undefined

const group = ref<Studycodemodel.Iteamusergroup[]>([])
onMounted(async () => {
  store.state.socket.on('api_import_user', api_import_user)
  group.value = await asyncfindteamusergroup({ teamid: p.teamInfo.ID });
})

const data = ref<string[][]>([]);
const tabledata = computed(() => {
  return data.value.map((e) => {
    const [学校名称, 名称, 手机号, 学籍号, 密码, 团队角色, 备注, 团队分组] = e;
    const iserror = jc(e);
    return {
      学校名称: 学校名称 ? String(学校名称).trim() : null,
      名称: 名称 ? String(名称).trim() : null,
      手机号: 手机号 ? String(手机号).trim() : null,
      学籍号: 学籍号 ? String(学籍号).trim() : null,
      密码: 密码 ? String(密码).trim() : '000000',
      团队id: p.teamInfo.ID,
      团队名称: p.teamInfo.name,
      团队角色: 团队角色 ? String(团队角色).trim() : null,
      备注,
      团队分组: 团队分组 ? String(团队分组).trim() : null,
      // 团队分组: 团队分组 ? group.value.find(e=>e.name === 团队分组)?.ID : null,
      iserror,
    };
  });
});

const team = ref<Studycodemodel.Iteam[]>([]);
const loading = ref(false);
const groupteam = computed(() => {
  const data = tabledata.value.map((e) => [e.团队id, e.团队名称]);
  const obj: Iobj<Studycodemodel.Iteam> = { ID: [], name: [], };
  for (let [a, b] of data) {
    if (!obj.ID.includes(a)) {
      obj.ID.push(a);
    }
    if (!obj.ID.includes(b)) {
      obj.name.push(b);
    }
  }
  return obj;
});
watch(() => groupteam.value, async (data) => {
  changeteam(data);
});

watch(() => p.close, (v) => {
  if (!v) {
    data.value = [];
  }
});

async function changeteam(data: Iobj<Studycodemodel.Iteam>) {
  loading.value = true;
  const ID = data.ID;
  const name = union(data.name);
  console.log(data)
  let t: Studycodemodel.Iteam[] = [];
  if (ID.length) {
    const { rows } = await asyncselectteams({ ID });
    t = rows;
  }
  if (name.length) {
    const { rows } = await asyncselectteams({ name });
    for (const row of rows) {
      const n = t.find((e) => e.ID === row.ID);
      if (!n) {
        t.push(row);
      }
    }
    for (const row of name) {
      const n = t.find((e) => e.name === row);
      if (!n) {
        t.push({ name: row });
      }
    }
  }
  team.value = t;
  loading.value = false;
}

function options(name: string) {
  return tabledata.value.filter((e) => e.团队名称 === name).map((e) => {
    return { value: e.名称, label: e.名称, };
  });
}

function jc(data: string[]) {
  const [学校名称 = '', 名称 = '', 手机号 = '', 学籍号 = '', 密码 = '123456', 团队角色 = '', 备注 = '', 团队分组 = ''] = data;
  if (!名称) {
    return "名称不合法";
  }
  if (手机号) {
    if (!isPhonenum.test(手机号)) {
      return "手机号不合法";
    }
  } else {
    if (!学籍号) {
      return "学籍号或者手机必须有一个";
    }
  }
  if (密码.length < 4) {
    return "密码长度最少4位";
  }
  if (团队分组 && !group.value.find(e => e.name === 团队分组)) {
    return "团队分组不合法，请填写正确的团队分组";
  }
  // if (!some([团队id, 团队名称])) {
  //   return "团队id或者团队名称必须填写一个";
  // }
  return false;
}
async function request({ file }: { file: File }) {
  data.value = await getfiletodata2<string>(file, 3);
  return true;
}
async function created(row: Studycodemodel.Iteam) {
  if (row.ID) return;
  if (!row.userid) {
    ElMessage.error("请选择团队创建者");
    return;
  }
}

async function add() {
  const t = tabledata.value.find(e => e.iserror);
  if (t && typeof t.iserror === "string") {
    ElMessage.error(t.iserror);
    return;
  }
  const f = team.value.find((e) => !e.userid);
  if (f) {
    ElMessage.error(`${f.name}中没有团队创建者`);
    return;
  }
  // return
  loading.value = true;
  ElNotification({ title: "开始添加用户", message: "开始添加用户", type: "info", });
  const teams: Studycodemodel.Iteam[] = team.value.map((e) => {
    const { ID, name, teamuser = [] } = e;
    const _teamuser: Studycodemodel.Iteamuser[] = tabledata.value.filter((f) => Number(f.团队id) == ID || name == f.团队名称).map((e) => {
      const t: Record<string, Studycodemodel.Iteamuser["isAdmin"]> = { 学生: 0, 教师: 2, 管理员: 1, };
      return {
        isAdmin: t[e?.团队角色 ? e?.团队角色 : "学生"] ? t[e?.团队角色 ? e?.团队角色 : "学生"] : 0,
        teamusergroupid: group.value.find(g => g.name === e?.团队分组)?.ID,
        user: {
          name: e?.名称,
          password: e?.密码,
          gid: e?.学籍号,
          phonenum: e?.手机号,
          remarks: e?.备注,
          info: { school: e?.学校名称, },
          xingming: e?.名称
        },
      };
    });
    return {
      ...e,
      teamuser: _teamuser,
      // 码客行
      tenant_id,
    };
  });
  if (teams.length) {
    store.state.socket.emit("api_import_user", { teams, });
  } else {
    store.state.socket.emit("api_import_user", {
      users: tabledata.value.map((e) => {
        return {
          name: e?.名称,
          password: e?.密码,
          gid: e?.学籍号,
          phonenum: e?.手机号,
          remarks: e?.备注,
          info: { school: e?.学校名称, },
          xingming: e?.名称,
          // 码客行
          tenant_id,
        };
      }),
    });
  }
}

const builddate = ref<Array<any[]>>([])

function api_import_user(e: {
  error: number;
  data: {
    importuser: Studycodemodel.Iuser[];
    user: Studycodemodel.Iuser[];
    _erru: Studycodemodel.Iuser[];
  };
  msg: string;
}) {
  if (e.error) {
    builddate.value.push([e.msg]);
    ElMessage.error(e.msg);
  } else {
    builddate.value.push(["注册成功用户"]);
    // builddate.value = builddate.value.concat(
    //   ...e.data.importuser
    //     .filter((_e, k) => k === 0)
    //     .map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.importuser.map((e) => Object.values(e).map(e => String(e)))
    );
    builddate.value.push(["之前添加成功用户"]);
    // builddate.value = builddate.value.concat(
    //   e.data.user.filter((e, k) => k === 0).map((e) => Object.keys(e))
    // );
    builddate.value = builddate.value.concat(
      e.data.user.map((e) => Object.values(e).map(e => String(e)))
    );
    builddate.value.push(["之前添加失败用户"]);
    builddate.value = builddate.value.concat(
      e.data._erru.map((e) => Object.values(e).map(e => String(e)))
    );
    getExceltodownload(builddate.value, "完成日志");
    ElMessage.success(e.msg);
    builddate.value = [];
    p.closeDrawer()
  }
}

function downloadTemplate() {
  window.open("https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/saas/%E5%9B%A2%E9%98%9F%E5%AF%BC%E5%85%A5%E6%88%90%E5%91%98%E6%A8%A1%E6%9D%BF.xlsx", "_blank");
}

</script>

<style scoped>
.upload-demo {
  display: inline-block;
}

.el-table th,
.el-table td {
  text-align: center;
}

.el-button {
  margin-right: 10px;
}
</style>
